package com.chainyoung.component_tmperson.ui.mvp.model;

import android.text.TextUtils;
import android.util.Log;

import com.chainyoung.common.appcommon.db.DbConstant;
import com.chainyoung.common.appcommon.entity.HdWalletCache;
import com.chainyoung.common.appcommon.hdwallet.EtherscanService;
import com.chainyoung.common.appcommon.hdwallet.HdWalletDAO;
import com.chainyoung.common.exception.ApiException;
import com.chainyoung.common.integration.IRepositoryManager;
import com.chainyoung.common.mvp.BaseModel;
import com.chainyoung.common.utils.RxUtils;
import com.chainyoung.component_tmperson.api.PersonService;
import com.chainyoung.component_tmperson.constant.PersonSystemConstant;
import com.chainyoung.component_tmperson.entity.BookMark;
import com.chainyoung.component_tmperson.entity.BrowseCache;
import com.chainyoung.component_tmperson.entity.CheckBookMarkResult;
import com.chainyoung.component_tmperson.ui.mvp.contract.HdWalletSendTransactionContract;
import com.chainyoung.component_tmperson.ui.mvp.contract.OtheAppSendTransactionContract;
import com.chainyoung.component_tmperson.ui.mvp.model.dao.BrowseDAO;
import com.google.gson.JsonObject;

import org.json.JSONObject;

import java.util.List;
import java.util.TreeMap;

import javax.inject.Inject;

import io.reactivex.Flowable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import okhttp3.ResponseBody;

public class OtherAppSendTransactionModel extends BaseModel implements OtheAppSendTransactionContract.Model {

    private BrowseDAO DAO = new BrowseDAO(mRepositoryManager.obtainRealmConfig(DbConstant.DB_NAME));
    private HdWalletDAO WalletDAO = new HdWalletDAO(mRepositoryManager.obtainRealmConfig(DbConstant.DB_NAME));

    @Inject
    OtherAppSendTransactionModel(IRepositoryManager repositoryManager) {
        super(repositoryManager);

    }


    @Override
    public Flowable<String> getGasPrice() {
        return mRepositoryManager.obtainRetrofitService(EtherscanService.class)
                .getGasPrice()
                .map(new Function<ResponseBody, String>() {
                    @Override
                    public String apply(@NonNull ResponseBody body) throws Exception {
                        return new JSONObject(body.string()).getString("result");
                    }
                });
    }

    @Override
    public Flowable<String> sendTransaction(String hex) {
        return mRepositoryManager.obtainRetrofitService(EtherscanService.class)
                .sendTransaction(hex)
                .map(new Function<ResponseBody, String>() {
                    @Override
                    public String apply(@NonNull ResponseBody body) throws Exception {
                        JSONObject jsonObject = new JSONObject(body.string());
                        if (jsonObject.has("result")) {
                            return jsonObject.getString("result");
                        } else if (jsonObject.has("error")) {
                            JSONObject errorObject = new JSONObject(jsonObject.getString("error"));
                            throw new ApiException(errorObject.getString("code"), errorObject.getString("message"));
                        }
                        return null;

                    }
                });
    }

    @Override
    public Flowable<String> getNonce(String addr) {
        return mRepositoryManager.obtainRetrofitService(EtherscanService.class)
                .getTransactionCount(addr)
                .map(new Function<ResponseBody, String>() {
                    @Override
                    public String apply(@NonNull ResponseBody body) throws Exception {
                        return new JSONObject(body.string()).getString("result");
                    }
                });
    }

    @Override
    public Flowable<CheckBookMarkResult> checkIsUrlCollected(TreeMap<String, Object> map) {
        return mRepositoryManager.obtainRetrofitService(PersonService.class)
                .checkBookmarkExsit(map)
                .compose(RxUtils.<CheckBookMarkResult>handleResult());
    }

    @Override
    public Flowable<List<BookMark>> delBookmark(TreeMap<String, Object> map) {
        return mRepositoryManager.obtainRetrofitService(PersonService.class)
                .delBookmark(map)
                .compose(RxUtils.<List<BookMark>>handleResult());
    }

    @Override
    public Flowable<List<BookMark>> addBookmark(TreeMap<String, Object> map) {
        return mRepositoryManager.obtainRetrofitService(PersonService.class)
                .addBookmark(map)
                .compose(RxUtils.<List<BookMark>>handleResult());
    }


    @Override
    public Flowable<BrowseCache> addBrowseCache(final BrowseCache item) {
        return DAO.addBrowseCache(item);
    }


    @Override
    public Flowable<HdWalletCache> addHdWalletCache(HdWalletCache item) {
        return WalletDAO.addHdWalletCache(item);
    }

    @Override
    public Flowable<List<HdWalletCache>> getAllHdWalletCaches(String coinType) {
        return WalletDAO.getHdWalletCaches(coinType);
    }

    @Override
    public Flowable<String> getSingleEthBalance(String addr) {
        return mRepositoryManager.obtainRetrofitService(EtherscanService.class)
                .getBalance(addr)
                .map(new Function<ResponseBody, String>() {
                    @Override
                    public String apply(@NonNull ResponseBody body) throws Exception {
                        String balance = new JSONObject(body.string()).getString("result");
                        if (balance.equals("0")) {
                            return "0";
                        } else {
                            return balance;
                        }
                    }
                });
    }


}

